package io.sunny.platform.backend.security.config.listener;

import io.sunny.platform.backend.utils.Sm4Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Map;

/**
 * @Author SUNNY
 * @Date 2025/7/17 16:10
 * @PackageName: io.sunny.platform.security.config.listener
 * @Description: 启动监听器还原明文配置项
 * @Version 1.0
 */
@Slf4j
public class EnvironmentDecryptListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    private static final Map<String, String> ENCRYPT_KEY_MAP = Map.of(
            "spring.datasource.dbu", "spring.datasource.url",
            "spring.datasource.usr", "spring.datasource.username",
            "spring.datasource.pwd", "spring.datasource.password",
            "spring.redis.host", "spring.redis.host",
            "spring.redis.port", "spring.redis.port",
            "spring.redis.pwd", "spring.redis.password",
            "spring.redis.db", "spring.redis.database"
    );

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        try {
            for (Map.Entry<String, String> entry : ENCRYPT_KEY_MAP.entrySet()) {
                String encryptKey = entry.getKey();
                String plainKey = entry.getValue();
                String encryptValue = environment.getProperty(encryptKey);
                String plainValue = Sm4Utils.decrypt(encryptValue);
                System.setProperty(plainKey, plainValue);
                log.info("解析加密信息：{}={} ==》 解析 ==》 {}={}", encryptKey, encryptValue, plainKey, plainValue);
            }
        } catch (Exception e) {
            log.error("配置解密失败: {}", e.getMessage());
        }
    }
}